<html>
<head>
<title>Selenium UI-Element Reference</title>
<style type="text/css">
body {
    margin-left: 5%;
    margin-right: 5%;
}
dt {
    font-weight: bolder;
}
dd {
    margin-top: 10px;
    margin-bottom: 10px;
}
pre {
    margin: 10px;
    padding: 10px;
    background-color: #eaeaea;
}
code {
    padding: 2px;
    background-color: #dfd;
}
table {
    border-collapse: collapse;
    border: solid 1px black;
}
th, td {
    border: solid 1px grey;
    padding: 5px;
}
.highlight {
    background-color: #eea;
}
.deprecated {
    font-style: italic;
    color: #c99;
}
</style>
</head>

<body>

<h1>Selenium UI-Element Reference</h1>

<h2>Introduction</h2>

<p>UI-Element is a Selenium feature that makes it possible to define a mapping between semantically meaningful names of elements on webpages, and the elements themselves. The mapping is defined using <a href="http://en.wikipedia.org/wiki/JSON">JavaScript Object Notation</a>, and may be shared both by the IDE and tests run via Selenium RC. It also offers a single point of update should the user interface of the application under test change.</p>

<h2>Terminology</h2>

<dl>
<dt>Page</dt>
<dd>A unique URL, and the contents available by accessing that URL. A page typically consists of several interactive page elements. A page may also be considered a DOM document object, complete with URL information.</dd>
<dt>Page element</dt>
<dd>An element on the actual webpage. Generally speaking, an element is anything the user might interact with, or anything that contains meaningful content. More specifically, an element is realized as a <a href="http://en.wikipedia.org/wiki/Document_Object_Model">Document Object Model (DOM)</a> node and its contents. So when we refer to a page element, we mean both of the following, at the same time:
<ul>
<li>something on the page</li>
<li>its DOM representation, including its relationship with other page elements</li>
</ul>
</dd>
<dt>Pageset</dt>
<dd>A set of pages that share some set of common page elements. For example, I might be able to log into my application from several different pages. If certain page elements on each of those pages appear similarly (i.e. their DOM representations are identical), those pages can be grouped into a pageset with respect to these page elements. There is no restriction on how many pagesets a given page can be a member of. Similarly, a UI element belong to multiple pagesets. A pageset is commonly represented by a <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> which matches the URL's that uniquely identify pages; however, there are cases when the page content must be considered to determine pageset membership. A pageset also has a name.</dd>
<dt>UI element</dt>
<dd>A mapping between a meaningful name for a page element, and the means to locate that page element's DOM node. The page element is located via a locator. UI elements belong to pagesets.</dd>
<dt>UI argument</dt>
<dd>An optional piece of logic that determines how the locator is generated by a UI element. Typically used when similar page elements appear multiple times on the same page, and you want to address them all with a single UI element. For example, if a page presents 20 clickable search results, the index of the search result might be a UI argument.</dd>
<dt>UI map</dt>
<dd>A collection of pagesets, which in turn contain UI elements. The UI map is the medium for translating between UI specifier strings, page elements, and UI elements.</dd>
<dt>UI specifier string</dt>
<dd>A bit of text containing a pageset name, a UI element name, and optionally arguments that modify the way a locator is constructed by the UI element. UI specifier strings are intended to be the human-readable identifier for page elements.</dd>
<dt>Rollup rule</dt>
<dd>Logic that describes how one or more Selenium commands can be grouped into a single command, and how that single command may be expanded into its component Selenium commands. The single command is referred to simply as a "rollup".</dd>
<dt>Command matcher</dt>
<dd>Typically folded into a rollup rule, it matches one or more Selenium commands and optionally sets values for rollup arguments based on the matched commands. A rollup rule usually has one or more command matchers.</dd>
<dt>Rollup argument</dt>
<dd>An optional piece of logic that modifies the command expansion of a rollup.</dd>
</dl>

<h2>The Basics</h2>

<h3>Getting Motivated</h3>

<p>Question: Why use UI-Element? Answer: So your testcases can look like this (boilerplate code omitted):</p>

<pre>
&lt;tr&gt;
    &lt;td&gt;open&lt;/td&gt;
    &lt;td&gt;/&lt;/td&gt;
    &lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
    &lt;td&gt;clickAndWait&lt;/td&gt;
    &lt;td&gt;<span class="highlight">ui=allPages::section(section=topics)</span>&lt;/td&gt;
    &lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
    &lt;td&gt;clickAndWait&lt;/td&gt;
    &lt;td&gt;<span class="highlight">ui=topicListingPages::topic(topic=Process)</span>&lt;/td&gt;
    &lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
    &lt;td&gt;clickAndWait&lt;/td&gt;
    &lt;td&gt;<span class="highlight">ui=subtopicListingPages::subtopic(subtopic=Creativity)</span>&lt;/td&gt;
    &lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
    &lt;td&gt;click&lt;/td&gt;
    &lt;td&gt;<span class="highlight">ui=subtopicArticleListingPages::article(index=2)</span>&lt;/td&gt;
    &lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
</pre>

<h3>Including the Right Files</h3>

<p>UI-Element is now fully integrated with Selenium. The only additional file that needs to be specified is your map definitions file. In the IDE, add it to the comma-delimited <em>Selenium Core extensions</em> field of the IDE options. A sample definition file created for the website <a href="http://alistapart.com">alistapart.com</a> is included in the distribution and is available here:</p>

<pre><a href="chrome://selenium-ide/content/selenium/scripts/ui-map-sample.js">chrome://selenium-ide/content/selenium/scripts/ui-map-sample.js</a></pre>

<p>You might want to experiment with the sample map to get a feel for UI-Element. For the Selenium RC, you have two options. The map file may be included in the <code>user-extensions.js</code> file specified at startup with the <code>-userExtensions</code> switch. Or, you may load it dynamically with the variant of the <code>setUserExtensionJs</code> command in your driver language, before the browser is started.</p>

<h3>Map Definitions File Syntax</h3>

<p>This is the general format of a map file:</p>

<pre>
var map = new UIMap();

map.addPageset({
    name: 'aPageset'
    , ... 
});
map.addElement('aPageset', { ... });
map.addElement('aPageset', { ... });
...

map.addPageset({
    name: 'anotherPageset'
    , ... 
});
...
</pre>

<p>The map object is initialized by creating a new <code>UIMap</code> object. Next, a pageset is defined. Then one or more UI elements are defined for that pageset. More pagesets are defined, each with corresponding UI elements. That's it!</p>

<h3>Pageset Shorthand</h3>

<p>The method signature of <code>addPageset()</code> is <em>(pagesetShorthand)</em>. <em>pagesetShorthand</em> is a JSON description of the pageset. Here's a minimal example:</p>

<pre>
map.addPageset({
    name: 'allPages'
    , description: 'contains elements common to all pages'
    , pathRegexp: '.*'
});
</pre>
    
<p>Here's a table containing information about the attributes of the Pageset object. The conditionally required or unrequired items are for IDE recording support only.</p>

<table>
<tr><th>Name</th>
    <th>Required?</th>
    <th>Description</th>
    <th>Example</th>
</tr>
<tr><td>name</td>
    <td>Yes</td>
    <td>(String) the name of the pageset. This should be unique within the map.</td>
    <td><pre>name: 'shopPages'</pre></td>
</tr>
<tr><td>description</td>
    <td>Yes</td>
    <td>(String) a description of the pageset. Ideally, this will give the reader an idea of what types of UI elements the pageset will have.</td>
    <td><pre>description: 'all pages displaying product'</pre></td>
</tr>
<tr><td>pathPrefix</td>
    <td>No</td>
    <td>(String) the path of the URL of all included pages in this pageset will contain this prefix. For example, if all pages are of the form http://www.example.com/<span class="highlight">gallery/</span>light-show/, the page prefix might be <code>gallery/</code> .</td>
    <td><pre>pathPrefix: 'gallery/'</pre></td>
</tr>
<tr><td>paths<br />pathRegexp</td>
    <td>Conditional</td>
    <td>(Array | String) either a list of path strings, or a string that represents a regular expression. One or the other should be defined, but not both. If an array, it enumerates pages that are included in the pageset. If a regular expression, any pages whose URL paths match the expression are considered part of the pageset. In either case, the part of the URL being matched (called the <em>path</em>) is the part following the domain, less any trailing slash, and not including the CGI parameters. For example:
    <ul>
    <li>http://www.example.com/<span class="highlight">articles/index.php</span></li>
    <li>http://www.example.com/<span class="highlight">articles/2579</span>?lang=en_US</li>
    <li>http://www.example.com/<span class="highlight">articles/selenium</span>/</li>
    </ul>
     The entire path must match (however, <code>pathPrefix</code> is taken into account if specified). If specified as a regular expression, the two regular expression characters <code>^</code> and <code>$</code> marking the start and end of the matched string are included implicitly, and should not be specified in this string. Please notice too that backslashes must be backslash-escaped in javascript strings.</td>
    <td><pre>paths: [
    'gotoHome.do'
    , 'gotoAbout.do'
    , 'gotoFaq.do'
]</pre>
        <pre>pathRegexp: 'goto(Home|About|Faq)\\.do'</pre>
</tr>
<tr><td>paramRegexps</td>
    <td>No</td>
    <td>(Object) a mapping from URL parameter names to regular expression strings which must match their values. If specified, the set of pages potentially included in this pageset will be further filtered by URL parameter values. There is no filtering by parameter value by default.</td>
    <td><pre>paramRegexps: {
    dept: '^[abcd]$'
    , team: 'marketing'
}</pre></td>
</tr>
<tr><td>pageContent</td>
    <td>Conditional</td>
    <td><p>(Function) a function that tests whether a page, represented by its document object, is contained in the pageset, and returns true if and only if this is the case. If specified, the set of pages potentially included in this pageset will be further filtered by content, after URL and URL parameter filtering.</p>
    <p>Since the URL is available from the document object (<code>document.location.href</code>), you may encode the logic used for the <code>paths</code> and <code>pathRegexp</code> attributes all into the definition of <code>pageContent</code>. Thus, you may choose to omit the former if and only if using <code>pageContent</code>. Of course, you may continue to use them for clarity.</td>
    <td><pre>pageContent: function(doc) {
    var id = 'address-tab';
    return doc.getElementById(id) != null;
}</pre></td>
</tr>
</table>

<h3><a name="ui-element-shorthand">UI-Element Shorthand</a></h3>

<p>The method signature of <code>addElement()</code> is <em>(pagesetName, uiElementShorthand)</em>. <em>pagesetName</em> is the name of the pageset the UI element is being added to. <em>uiElementShorthand</em> is a complete JSON description of the UI element object in shorthand notation.</p>

<p>In its simplest form, a UI element object looks like this:</p>

<pre>
map.addElement('allPages', {
    name: 'about_link'
    , description: 'link to the about page'
    , locator: "//a[contains(@href, 'about.php')]"
});
</pre>

<p>Here's a table containing information about the attributes of the UI element object. The asterisk (<code>*</code>) means any string:</p>

<table>
<tr><th>Name</th>
    <th>Required?</th>
    <th>Description</th>
    <th>Example</th>
</tr>
<tr><td>name</td>
    <td>Yes</td>
    <td>(String) the name of the UI element</td>
    <td><pre>name: 'article'</pre></td>
</tr>
<tr><td>description</td>
    <td>Yes</td>
    <td>(String) a description of the UI element. This is the main documentation for this UI element, so the more detailed, the better.</td>
    <td><pre>description: 'front or issue page link to article'</pre></td>
</tr>
<tr><td>args</td>
    <td>No</td>
    <td>(Array) a list of arguments that modify the <code>getLocator()</code> method. If unspecified, it will be treated as an empty list.</td>
    <td><pre>[
    { name: 'index'
    , description: 'the index of the author, by article'
    , defaultValues: range(1, 5) }
]</pre><em>See section below elaborating on attributes of argument objects.</em></td>
</tr>
<tr><td>locator<br />getLocator()<br /><span class="deprecated">xpath</span<br /><span class="deprecated">getXPath()</span></td>
    <td>Yes</td>
    <td><p>(String | Function) either a fixed locator string, or a function that returns a locator string given a set of arguments. One or the other should be defined, but not both. Under the sheets, the <code>locator</code> attribute eventually gets transcripted as a <code>getLocator()</code> function.</p><p><span class="deprecated">As of ui0.7, <code>xpath</code> and <code>getXPath()</code> have been deprecated. They are still supported for backward compatibility.</span></p></td>
    <td><pre>locator: 'submit'</pre>
        <pre>getLocator: function(args) {
    return 'css=div.item:nth-child(' + args.index + ')'
        + ' > h5 > a';
}</pre>
        <pre>getLocator: function(args) {
    var label = args.label;
    var id = this._idMap[label];
    return '//input[@id=' + id.quoteForXPath() + ']';
}</pre></td>
<tr><td>genericLocator<br />getGenericLocator</td>
    <td>No</td>
    <td><p>(String | Function) either a fixed locator string, or a function that returns a locator string. If a function, it should take no arguments.</p><p>You may experience some slowdown when recording on pages where individual UI elements have many default locators (due to many permutations of default values over multiple arguments). This is because each default locator is potentially evaluated and matched against the interacted page element. This becomes especially problematic if several UI elements have this characteristic.</p><p>By specifying a generic locator, you give the matching engine a chance to skip over UI elements that definitely don't match. The default locators for skipped elements will not be evaluated unless the generic locator matches the interacted page element..</p></td>
    <td><pre>genericLocator: "//table[@class='ctrl']"
    + "/descendant::input"</pre>
        <pre>getGenericLocator: function() {
    return this._xpathPrefix + '/descendant::a';
}</pre>
</tr>
<tr><td>getOffsetLocator</td>
    <td>No</td>
    <td><p>(Function) a function that returns an offset locator. The locator is offset from the element identified by a UI specifier string. The function should take this element, and the interacted page element, as arguments, and have the method signature <code>getOffsetLocator(locatedElement, pageElement)</code>. If an offset locator can't be found, a value that evaluates to <code>false</code> must be returned.</p><p>A convenient default function <code>UIElement.defaultOffsetLocatorStrategy</code> is provided so you don't have to define your own. It uses several typical strategies also employed by the IDE recording when recording normally. See the Advanced Topics section below for more information on offset locators.</p></td>
    <td><pre>getOffsetLocator: <span class="highlight">UIElement.defaultOffsetLocatorStrategy</span></pre>
        <pre>getOffsetLocator:
    function(locatedElement, pageElement) {
    if (pageElement.parentNode == locatedElement) {
        return '/child::' + pageElement.nodeName;
    }
    return null;
}</pre></td>
<tr><td>testcase*</td>
    <td>No</td>
    <td>(Object) a testcase for testing the implementation of the <code>getLocator()</code> method. As many testcases as desired may be defined for each UI element. They must all start with the string "testcase".</td>
    <td><pre>testcase1: {
    xhtml: '&lt;div class="item"&gt;&lt;h5&gt;'
        + '&lt;a expected-result="1" /&gt;&lt;/h5&gt;&lt;/div&gt;'
}</pre><em>See section below elaborating on testcases.</em></td>
</tr>
<tr><td>_*</td>
    <td>No</td>
    <td>(Any data type) a "local variable" declared for the UI element. This variable will be available both within the <code>getLocator()</code> method of the UI element, and any <code>getDefaultValues()</code> methods of the arguments via the <code>this</code> keyword. They must all start with an underscore "_".</td>
    <td><pre>_labelMap: {
    'Name': 'user'
    , 'Email': 'em'
    , 'Phone': 'tel'
}</pre></td>
</tr>
</table>

<h3>UI-Argument Shorthand</h3>

<p>UI arguments are defined as part of UI elements, and help determine how an XPath is generated. A list of arguments may be defined within the UI element JSON shorthand. Here's an example of how that might look:</p>

<pre>
map.addElement('searchPages', {
    name: 'result'
    , description: 'link to a result page'
    , args: [
        {
            name: 'index'
            , description: 'the index of the search result'
            , defaultValues: range(1, 21)
        }
        , {
            name: 'type'
            , description: 'the type of result page'
            , defaultValues: [ 'summary', 'detail' ]
        }
    ]
    , getLocator: function(args) {
        var index = args['index'];
        var type = args['type'];
        return "//div[@class='result'][" + index + "]"
            + "/descendant::a[@class='" + type + "']";
    }
});
</pre>

<p>In the above example, two arguments are defined, <code>index</code> and <code>type</code>. Metadata is provided to describe them, and default values are also specified. FInally, the <code>getLocator()</code> method is defined. The behavior of the method depends on the values of the arguments that are passed in.</p>

<p>Default values come into play when recording tests using the Selenium IDE. When you interact with a page element in recording mode, the IDE uses all the locator strategies at its disposal to deduce an appropriate locator string for that element. UI-Element introduces a new <code>ui</code> locator strategy. When applying this strategy using a particular UI element, Selenium generates a list of XPaths to try by permuting the arguments of that UI element over all default values. Here, the default values <em>{ 1, 2, 3, 4 .. 20 }</em> are given for the <code>index</code> argument using the special <code>range()</code> function, and the values <em>{ summary, detail }</em> are given for the <code>type</code> argument in standard javascript array notation. If you don't intend to use the IDE, go ahead and set the default values to the empty array <code>[]</code>.</p>

<p>Here's a table containing information about the attributes of the UI argument object.</p>

<table>
<tr><th>Name</th>
    <th>Required?</th>
    <th>Description</th>
    <th>Example</th>
</tr>
<tr><td>name</td>
    <td>Yes</td>
    <td>(String) the name of the argument. This will be the name of the property of the object passed into the parent UI element's <code>getLocator()</code> method containing the argument value.</td>
    <td><pre>name: 'index'</pre></td>
</tr>
<tr><td>description</td>
    <td>Yes</td>
    <td>(String) a description for the argument.</td>
    <td><pre>description: 'the index of the article'</pre></td>
</tr>
<tr><td>defaultValues<br/>getDefaultValues()</td>
    <td>Yes</td>
    <td><p>(Array | Function) either an array of string or numerical values, or a function that returns an array of string or numerical values. One or the other should be defined, but not both. Under the sheets, the <code>defaultValues</code> attribute eventually gets transcripted as a <code>getDefaultValues()</code> function.</p><p>The method signature of the function is <code>getDefaultValues(inDocument)</code>. <code>inDocument</code> is the current document object of the page at time of recording. In cases where the default values are known a priori, <code>inDocument</code> need not be used. If the default values of all arguments of a UI element are known a priori, the list of default locators for the element may be precalculated, resulting in better performance. If <code>inDocument</code> is used, in cases where the current document is inspected for valid values, the element's default locators are calculated once for every recordable event.</p></td>
    <td><pre>defaultValues: [ 'alpha', 'beta', 'unlimited' ]</pre>
        <pre>getDefaultValues: function() {
    return keys(this._idMap);
}</pre>
        <pre>getDefaultValues: function(inDocument) {
    var defaultValues = [];
    var links = inDocument
        .getElementsByTagName('a');
    for (var i = 0; i < links.length; ++i) {
        var link = links[i];
        if (link.className == 'category') {
            defaultValues.push(link.innerHTML);
        }
    }
    return defaultValues;
}</pre></td>
</tr>
</table>

<h3>About <code>this</code></h3>

<p>You may have noticed usage of the <code>this</code> keyword in the examples above, specifically in the <code>getLocator()</code> and <code>getDefaultValues()</code> methods. Well, what exactly is <code>this</code>?</p>

<p>The answer is: it depends. The object referred to by <code>this</code> changes depending on the context in which it is being evaluated. At the time of object creation using <code>addPageset()</code> or <code>addElement()</code>, it refers to the <code>window</code> object of the Selenium IDE, which isn't useful at all. However, subsequently any time <code>getLocator()</code> is called, its <code>this</code> references the UI element object it's attached too. Thus, using <code>this</code>, any "local variables" defined for the UI element may be accessed. Similarly, when <code>getDefaultValues()</code> is called, its <code>this</code> references the UI argument object it's attached too. But ... what "local variables" are accessible by the from <code>getDefaultValues()</code>?</p>

<p>There's a little magic here. If you defined your local variables as prescribed in the above <a href="#ui-element-shorthand">UI-Element Shorthand</a> section, starting with an underscore, those variable are automatically made available to the UI argument via its <code>this</code> keyword. Note that this isn't standard javascript behavior. It's implemented this way to clear out clutter in the method definitions and to avoid the use of global variables for lists and maps used within the methods. It is sometimes useful, for example, to define an object that maps human-friendly argument values to DOM element <code>id</code>'s. In such a case, <code>getDefaultValues()</code> can be made to simply return the <code>keys()</code> (or property names) of the map, while the <code>getLocator()</code> method uses the map to retrieve the associated <code>id</code> to involve in the locator.</p>

<p>Also note that <code>this</code> only behaves this way in the two mentioned methods, <code>getLocator()</code> and <code>getDefaultValues()</code>; in other words you can't reference the UI element's local variables using <code>this</code> outside of methods.</p>

<p>If you're interested, here's some <a href="http://www.digital-web.com/articles/scope_in_javascript/">additional reading on javascript scope</a>.</p>

<h2>Advanced Topics</h2>

<h3>Testcases</h3>

<p>You can write testcases for your UI element implementations that are run every time the Selenium IDE is started. Any testcases that fail are reported on. The dual purpose of writing testcases is to both validate the <code>getLocator()</code> method against a representation of the real page under test, and to give a visual example of what the DOM context of a page element is expected to be.</p>

<p>A testcase is an object with a required <code>xhtml</code> property (String), and a required <code>args</code> property (Object). An example is due:</p>

<pre>
testcase1: {
    args: { line: 2, column: 3 }
    , xhtml: '&lt;table id="scorecard"&gt;'
        + '&lt;tr class="line" /&gt;'
        + '&lt;tr class="line"&gt;&lt;td /&gt;&lt;td /&gt;&lt;td expected-result="1" /&gt;&lt;/tr&gt;'
        + '&lt;/table&gt;'
}
</pre>

<p>The <code>args</code> property specifies the object to be passed into the UI element's <code>getLocator()</code> method to generate the test locator, which is then applied to the <code>xhtml</code>. If evaluating the locator on the XHTML document returns a DOM node with the <code>expected-result</code> attribute, the testcase is considered to have passed.</p>

<p>The <code>xhtml</code> property must represent a complete XML document, sans <code>&lt;html&gt;</code> tags, which are automatically added. The reason this is necessary is that the text is being converted into an XPath evaluable DOM tree via Mozilla's native XML parser. Unfortunately, there is no way to generate a simple HTML document, only XML documents. This means that the content of the <code>xhtml</code> must be well-formed. <span class="highlight">Tags should also be specified in lowercase.</span></p>

<h3>Fuzzy Matching</h3>

<p>Here's a real-world example of where fuzzy matching is important:</p>

<pre>
&lt;table&gt;
&lt;tr onclick="showDetails(0)"&gt;
    &lt;td&gt;Brahms&lt;/td&gt;
    &lt;td&gt;Viola Quintet&lt;/td&gt;
&lt;/tr&gt;
&lt;tr onclick="showDetails(1)"&gt;
    &lt;td&gt;Saegusa&lt;/td&gt;
    &lt;td&gt;Cello 88&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
</pre>

<p>Imagine I'm recording in the IDE. Let's say I click on "Cello 88". The IDE would create locator for this action like <code>//table/tr[2]/td[2]</code>. Does that mean that my <code>getLocator()</code> method should return the same XPath?</p>

<p>Clearly not. Clicking on either of the table cells for the second row has the same result. I would like my UI element generated XPath to be <code>//table/tr[2]</code> . However, when recording, the page element that was identified as being acted upon was the table cell, which doesn't match my UI element XPath, so the <code>ui</code> locator strategy will fail to auto-populate. What to do?</p>

<p>Fuzzy matching to the rescue! Fuzzy matching is realized as a fuzzy matcher function that returns true if a target DOM element is considered to be equivalent to a reference DOM element. The reference DOM element would be the element specified by the UI element's generated XPath. Currently, the fuzzy matcher considers it a match if:

<ul>
<li>the elements are the same element,</li>
<li>the reference element is an anchor (<code>&lt;a&gt;</code>) element, and the target element is a descendant of it; or</li>
<li>the reference element has an <code>onclick</code> attribute, and the target element is a descendant of it.</li>
</ul>

<p>This logic may or may not be sufficient for you. The good news is, it's very easy to modify. Look for the definition of <code>BrowserBot.prototype.locateElementByUIElement.is_fuzzy_match</code> in <code>ui-element.js</code> .</p>

<h3>Offset Locators</h3>

<p>Offset locators are locators that are appended to UI specifier strings to form composite locators. They can be automatically deduced by the IDE recorder for UI elements that have specified a <code>getOffsetLocator</code> function. This feature may be useful if your pages contain too many elements to write UI elements for. In this case, offset locators allow you to define UI elements that "anchor" other elements. Given the following markup:</p>

<pre>&lt;form name="contact_info"&gt;
    &lt;input type="text" name="foo" /&gt;
    &lt;textarea name="bar"&gt;&lt;/textarea&gt;
    &lt;input type="submit" value="baz" /&gt;
&lt;/form&gt;</pre>

<p>Assume that a UI element has been defined for the form element. Then the following locators containing offset locators and "anchored" off this element would be recorded using the default offset locator function (<code>UIElement.defaultOffsetLocatorStrategy</code>):</p>

<pre>ui=contactPages::contact_form()<span class="highlight">->//input[@name='foo']</span>
ui=contactPages::contact_form()<span class="highlight">->//textarea[@name='bar']</span>
ui=contactPages::contact_form()<span class="highlight">->//input[@value='baz']</span></pre>

<p>The character sequence <code>-&gt;</code> serves to delimit the offset locator from the main locator. For this reason, the sequence should not appear in the main locator, or else ambiguity will result.</p>

<p>When recording with the IDE, no preference is given to matching plain vanilla UI specifier strings over ones that have offset locators. In other words, if a page element could be specified both by a UI specifier string for one UI element, and by one augmented by an offset locator for a different UI element, there is no guarantee that one or the other locator will be recorded.</p>

<p>Currently, <span class="highlight">only XPath is supported as an offset locator type</span>, as it is the only locator for which a context node can be specified at evaluation time. Other locator strategies may be supported in the future.</p>

<h3>Rollup Rules</h3>

<p>Question: Why use rollup rules? Answer: Remember the testcase from the "Getting Motivated" section above? With rollups, that testcase can be condensed into this:</p>

<pre>
&lt;tr&gt;
    &lt;td&gt;open&lt;/td&gt;
    &lt;td&gt;/&lt;/td&gt;
    &lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
    &lt;td&gt;rollup&lt;/td&gt;
    &lt;td&gt;<span class="highlight">navigate_to_subtopic_article</span>&lt;/td&gt;
    &lt;td&gt;<span class="highlight">index=2, subtopic=Creativity</span>&lt;/td&gt;
&lt;/tr&gt;
</pre>

<p>It's inevitable that certain sequences of Selenium commands will appear in testcases over and over again. When this happens, you might wish to group several fine-grained commands into a single coarser, more semantically meaningful action. In doing so, you would abstract out the execution details for the action, such that if they were to change at some point, you would have a single point of update. In UI-Element, such actions are given their own command, called <code>rollup</code>. In a sense, rollups are a natural extension of the <code>ui</code> locator.</p>

<p>UI-Element is designed with the belief that the IDE can be a useful tool for writing testcases, and need not be shunned for lack of functionality. A corollary belief is that you should be able to drive your RC test in the language of your choice. The execution of the <code>rollup</code> command by the Selenium testrunner produces the component commands, which are executed in a new context, like a function call. The logic of the rollup "expansion" is written in javascript. Corresponding logic for inferring a rollup from a list of commands is also written in javascript. Thus, the logic can be incorporated into any of the family of Selenium products as a user extension. Most notably, the IDE is made viable as a testcase creation tool that understands both how rollups expand to commands, and also how rollup rules can be "applied" to commands to reduce them to rollups.</p>

<p>Rollup rule definitions appear in this general format:</p>

<pre>
var manager = new RollupManager();

manager.addRollupRule({ ... });
manager.addRollupRule({ ... });
...
</pre>

<p>In a relatively simple form, a rollup rule looks like this:</p>

<pre>
manager.addRollupRule({
    name: 'do_search'
    , description: 'performs a search'
    , args: [
        name: 'term'
        , description: 'the search term'
    ]
    , commandMatchers: [
        {
            command: 'type'
            , target: 'ui=searchPages::search_box\\(.+'
            , updateArgs: function(command, args) {
                var uiSpecifier = new UISpecifier(command.target);
                args.term = uiSpecifier.args.term;
                return args;
            }
        }
        , {
            command: 'click.+'
            , target: 'ui=searchPages::search_go\\(.+'
        }
    ]
    , getExpandedCommands: function(args) {
        var commands = [];
        var uiSpecifier = new UISpecifier(
            'searchPages'
            , 'search_box'
            , { term: args.term });
        commands.push({
            command: 'type'
            , target: 'ui=' + uiSpecifier.toString()
        });
        commands.push({
            command: 'clickAndWait'
            , target: 'ui=searchPages::search_go()'
        });
        return commands;
    }
});
</pre>

<p>In the above example, a rollup rule is defined for performing a search. The rule can be "applied" to two consecutive commands that match the <code>commandMatchers</code>. The rollup takes one argument, <code>term</code>, and expands back to the original two commands. One thing to note is that the second command matcher will match all commands starting with <code>click</code>. The rollup will expand that command to a <code>clickAndWait</code>.</p>

<p>Here's a table containing information about the attributes of the rollup rule object.</p>

<table>
<tr><th>Name</th>
    <th>Required?</th>
    <th>Description</th>
    <th>Example</th>
</tr>
<tr><td>name</td>
    <td>Yes</td>
    <td>(String) the name of the rollup rule. This will be the target of the resulting <code>rollup</code> command.</td>
    <td><pre>name: 'do_login'</pre></td>
</tr>
<tr><td>description</td>
    <td>Yes</td>
    <td>(String) a description for the rollup rule.</td>
    <td><pre>description: 'logs into the application'</pre></td>
</tr>
<tr><td>alternateCommand</td>
    <td>No</td>
    <td>(String) specifies an alternate usage of rollup rules to replace commands. This string is used to replace the command name of the first matched command.</td>
    <td><pre>alternateCommand: 'clickAndWait'</pre></td>
</tr>
<tr><td>pre</td>
    <td>No</td>
    <td>(String) a detailed summary of the preconditions that must be satisfied for the rollup to execute successfully. This metadata is easily viewable in the IDE when the rollup command is selected.</td>
    <td><pre>pre: 'the page contains login widgets'</pre></td>
</tr>
<tr><td>post</td>
    <td>No</td>
    <td>(String) a detailed summary of the postconditions that will exist after the rollup has been executed.</td>
    <td><pre>post: 'the user is logged in, or is \
directed to a login error page'</pre></td>
</tr>
<tr><td>args</td>
    <td>Conditional</td>
    <td><p>(Array) a list of arguments that are used to modify the rollup expansion. These are similar to UI arguments, with the exception that <code>exampleValues</code> are provided, instead of <code>defaultValues</code>. Here, example values are used for reference purposes only; they are displayed in the rollup pane in the IDE.</p><p>This attribute may be omitted if no <code>updateArgs()</code> functions are defined for any command matchers.</td>
    <td><pre>args: {
    name: 'user'
    , description: 'the username to login as'
    , exampleValues: [
        'John Doe'
        , 'Jane Doe'
    ]
}</pre></td>
</tr>
<tr><td>commandMatchers<br />getRollup()</td>
    <td>Yes</td>
    <td><p>(Array | Function) a list of command matcher definitions, or a function that, given a list of commands, returns either 1) a rollup command if the rule is considered to match the commands (starting at the first command); or 2) false. If a function, it should have the method signature <code>getRollup(commands)</code>, and the returned rollup command (if any) must have the <code>replacementIndexes</code> attribute, which is a list of array indexes indicating which commands in the <code>commands</code> parameter are to be replaced.</p>
    <p>If you don't intend on using the IDE with your rollups, go ahead and set this to the empty array <code>[]</code>.</p></td>
    <td><pre>commandMatchers: [
    {
        command: 'type'
        , target: 'ui=loginPages::user\\(.+'
        , value: '.+'
        , minMatches: 1
        , maxMatches: 1
        , updateArgs:
            function(command, args) {
            args.user = command.value;
            return args;
        }
    }
]</pre>
        <pre>// this is a simplistic example, roughy
// equivalent to the commandMatchers
// example above. The <span class="highlight">to_kwargs()</span> function
// is used to turn an arguments object into
// a keyword-arguments string.
getRollup: function(commands) {
    var command = commands[0];
    var re = /^ui=loginPages::user\(.+/;
    if (command.command == 'type' &&
        re.test(command.target) &&
        command.value) {
        var args = { user: command.value };
        return {
            command: 'rollup'
            , target: this.name
            , value: to_kwargs(args)
            , replacementIndexes: [ 0 ]
        };
    }
    return false;
}</pre><em>See section below elaborating on command matcher objects.</em></td>
</tr>
<tr><td>expandedCommands<br />getExpandedCommands()</td>
    <td>Yes</td>
    <td><p>(Array | Function) a list of commands the rollup command expands into, or a function that, given an argument object mapping argument names to values, returns a list of expanded commands. If a function, it should have the method signature <code>getExpandedCommands(args)</code>.</p><p>Each command in the list of expanded commands should contain a <code>command</code> attribute, which is the name of the command, and optionally <code>target</code> and <code>value</code> attributes, depending on the type of command.</p><p>It is expected that providing a fixed list of expanded commands will be of limited use, as rollups will typically contain commands that have arguments, requiring more sophisticated logic to expand.</td>
    <td><pre>expandedCommands: [
    {
        command: 'check'
        , target: 'ui=termsPages::agree\\(.+'
    }
    , {
        command: 'clickAndWait'
        , target: 'ui=termsPages::submit\\(.+'
    }
]</pre>
        <pre>getExpandedCommands: function(args) {
    var commands = [];
    commands.push({
        command: 'type'
        , target: 'ui=loginPages::user()'
        , value: args.user
    });
    commands.push({
        command: 'type'
        , target: 'ui=loginPages::pass()'
        , value: args.pass
    });
    commands.push({
        command: 'clickAndWait'
        , target: 'ui=loginPages::submit()'
    });
    commands.push({
        command: 'verifyLocation'
        , target: 'regexp:.+/home'
    });
    return commands;
}</pre>
        <pre>// if using alternateCommand
expandedCommands: []
</pre></td>
</tr>
</table>

<p>The user should be able to freely record commands in the IDE, which can be collapsed into rollups at any point by applying the defined rollup rules. Healthy usage of the <code>ui</code> locator makes commands easy to match using command matcher definitions. Command matchers simplify the specification of a command match. In basic usage, for a rollup rule, you might specify 3 command matchers: <em>M1</em>, <em>M2</em>, and <em>M3</em>, that you intend to match 3 corresponding commands, <em>C1</em>, <em>C2</em>, and <em>C3</em>. In more complex usage, a single command matcher might match more than one command. For example, <em>M1</em> matches <em>C1</em> and <em>C2</em>, <em>M2</em> matches <em>C3</em>, and <em>M3</em> matches <em>C4</em>, <em>C5</em>, and <em>C6</em>. In the latter case, you would want to track the matches by updating argument values in the command matchers' <code>updateArgs()</code> methods.</p>

<p>Here are the required and optional fields for command matcher objects:</p>

<table>
<tr><th>Name</th>
    <th>Required?</th>
    <th>Description</th>
    <th>Example</th>
</tr>
<tr><td>command</td>
    <td>Yes</td>
    <td>(String) a simplified regular expression string that matches the command name of a command. The special regexp characters <code>^</code> and <code>$</code> are automatically included at the beginning and end of the string, and therefore should not be explicitly provided.</td>
    <td><pre>command: 'click.+'</pre>
        <pre>command: 'rollup'</pre></td>
</tr>
<tr><td>target</td>
    <td>Yes</td>
    <td>(String) a simplified regular expression string that matches the target of a command. Same rules as for the <code>command</code> attribute.</td>
    <td><pre>target: 'btnG'</pre>
        <pre>// special regexp characters must be
// escaped in regexp strings. Backslashes
// always need to be escaped in javascript
// strings.
target: 'ui=loginPages::user\\(.+'
    </pre></td>
</tr>
<tr><td>value</td>
    <td>No</td>
    <td>(String) a simplified regular expression string that matches the value of a command. Same rules as for the <code>command</code> attribute.</td>
    <td><pre>value: '\\d+'</pre>
        <pre>value: (?:foo|bar)</pre></td>
</tr>
<tr><td>minMatches</td>
    <td>No</td>
    <td>(Number) the minimum number of times this command matcher must match consecutive commands for the rollup rule to match a set of commands. If unspecified, the default is 1. If <code>maxMatches</code> is also specified, <code>minMatches</code> must be less than or equal to it.</td>
    <td><pre>minMatches: 2</pre></td>
</tr>
<tr><td>maxMatches</td>
    <td>No</td>
    <td>(Number) the maximum number of times this command matcher is allowed to match consecutive commands for the rollup rule. If unspecified, the default is 1.</td>
    <td><pre>maxMatches: 2</pre></td>
</tr>
<tr><td>updateArgs()</td>
    <td>No</td>
    <td><p>(Function) updates an arguments object when a match has been found, and returns the updated arguments object. This method is used to keep track of the way in which one or more commands were matched. When a rollup rule is successfully applied, any argument name-value pairs are stored as the rollup command's value. At time of expanding the rollup command, the command's value is converted back to an arguments object, which is passed to the rollup rule's <code>getExpandedCommands()</code> method.</p><p>This method must have the following method signature: <code>updateArgs(command, args)</code>, where <code>command</code> is the command object that was just matched, and <code>args</code> is the arguments object for the current trial application of the parent rollup rule.</td>
    <td><pre>// reused from above
updateArgs: function(command, args) {
    args.user = command.value;
    return args;
}</pre>
        <pre>// for multiple matches
updateArgs: function(command, args) {
    if (!args.clickCount) {
        args.clickCount = 0;
    }
    ++args.clickCount;
    return args;
}</pre>
        <pre>// another example from above (modified).
// If you need to parse a UI specifier,
// instantiate a new <span class="highlight">UISpecifier</span> object with the
// locator. To do it by the book, you should
// first strip off the "ui=" prefix. If you just
// want to inspect the UI specifier's args, you
// can safely skip this step.
updateArgs: function(command, args) {
    var s = command.target.replace(/^ui=/, '');
    var uiSpecifier = new UISpecifier(s);
    args.term = uiSpecifier.args.term;
    return args;
}</pre>
        <pre>// example from sample map file. If you're
// matching a rollup command that has arguments,
// you'll want to parse them. The easiest way
// to do this is with the <span class="highlight">parse_kwargs()</span>
// function, which has its roots in python.
updateArgs: function(command, args) {
    var args1 = parse_kwargs(command.value);
    args.subtopic = args1.subtopic;
    return args;
}</pre></td>
</tr>
</table>

<p>Too much mumbo jumbo?</p>

<p>To see rollup rules in action in the IDE, use the included sample map with UI-Element (see instructions above in the "Including the Right Files" section), and grab the listing of 4 commands from the "Getting Motivated" section, above. Under the <em>Source</em> tab of the IDE, paste the commands in between the <code>&lt;tbody&gt;</code> and <code>&lt;/tbody&gt;</code> tags. Now switch back to the <em>Table</em> tab, and click the new <span class="highlight">purple spiral button</span>; this is the "Apply rollup rules" button. If done correctly, you should be prompted when rollup rule matches are found. Go ahead - go to the <a href="http://alistapart.com">alistapart.com</a> site and try executing the rollups!</p>

<h2>Release Notes</h2>

<h3>Core-1.0</h3>

<ul>
<li>UI-Element is now completely integrated into Selenium Core.</li>
<li>Added offset locators. Modified the delimiter to be <code>-&gt;</code>.</li>
<li><code>getDefaultValues()</code> can dynamically construct a list of values and assume that a <code>document</code> object is being passed in.</li>
<li>Arguments in UI specifier strings are presented in the same order as they are defined in the mapping file (no longer alphabetically).</li>
<li>Allow generic locators to be specified, potentially improving recording performance when there are many UI arguments.</li>
<li>Updated documentation.</li>
<li>Many other fixes.</li>
</ul>

<h3>ui0.7</h3>

<ul>
<li>Changed extensions id and homepage to avoid conflicting with standard Selenium IDE distribution.</li>
<li>Added rollup button.</li>
<li>Added UI-Element and Rollup panes, with beautiful colors and formatting.</li>
<li>Updated referenced version of Selenium Core to 0.8.3, and RC to 0.9.2 .</li>
<li>Added <code>quoteForXPath()</code> to <code>String</code> prototype.</li>
<li>Made XPath uppercasing much more robust. It is now backed by the ajaxslt library. Uppercasing is no longer required by UI-Element. It is used to demonstrate how XPath transformations may be used to improve XPath evaluation performance when using the javascript engine. See <a href="http://groups.google.com/group/google-ajax-discuss/browse_thread/thread/f7a7a2014a6415d4">this thread on XPath performance</a>.
<li>Added new <code>rollup</code> Selenium command and associated functionality with the RollupManager object.</li>
<li>Deprecated <code>getXPath()</code> and <code>xpath</code> in favor of <code>getLocator()</code> and <code>locator</code> in the UI-Element shorthand. Testcases now work with locator types other than XPath (implicit, CSS, etc.).</li>
<li>UI element testcases are now truly XHTML. All content is considered inner HTML of the html element, which is automatically generated. This supports the use of alternate locator types described in the above bullet.</li>
<li>Global variables introduced by UI-Element are now properties of the variable <code>GLOBAL</code>. You can now name your map <code>uiMap</code> if you wish.</li>
<li>Updated the sample map, including demonstration of implicit and CSS locators, Rollup Rules, and usage of <code>quoteForXPath()</code>.</li>
<li>Improved auto-population of target dropdown with UI element locators and rollup names. The population logic is as follows: when a command is loaded from a file or inserted without having been recorded, all UI element locators are shown. After a command recorded or executed, only UI element locators for pagesets that match the page at time of recording or execution will be shown.</li>
<li>Made UI element testcase args mandatory. This reduces the startup time for the IDE, and improves testcase readability.</li>
<li>Updated documentation. Added this release notes section.</li>
</ul>

<h2>Final Thoughts</h2>

<p>Catch UI-Element news in the <a href="http://ttwhy.org/home/blog/category/selenium/">Selenium category of my blog</a>. You can also find me on the <a href="http://clearspace.openqa.org/people/gyrm">OpenQA Forums</a>.</p>

<p><em>- Haw-Bin Chai</em></p>

</body>
</html>
